<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Distance
{
	private $_CI;

    public function __construct()
    {
		$this->_CI = & get_instance();

		log_message('debug', "FOX: Authentication library Class Initialized");

    }
	
	/** 
	 * 根据起点坐标和终点坐标测距离[http://lbs.qq.com/webservice_v1/guide-distance.html] 
	 * @param  [array]   $from [起点坐标(经纬度),例如:array(118.012951,36.810024)] 
	 * @param  [array]   $to [终点坐标(经纬度)] 
	 * @return [string]  距离数值 
	 */  
	function get_baidu_distance($from,$to){  
		sort($from);  
		sort($to);  
		$from = implode(",", $from);  
		$to = implode(",", $to);  
		$curl = 'http://apis.map.qq.com/ws/distance/v1/?mode=driving&from='.$from.'&to='.$to.'&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';  
		$content = request($curl);  
		$result = json_decode($content,true);  
		return $result['result']['elements']['distance'];  
	}  
	
	/**
	*  @desc 根据两点间的经纬度计算距离
	*  @param float $lat 纬度值
	*  @param float $lng 经度值
	*/
	 function getDistance($lat1, $lng1, $lat2, $lng2)
	 {
		 $earthRadius = 6367000; //approximate radius of earth in meters

		 /*
		   Convert these degrees to radians
		   to work with the formula
		 */

		 $lat1 = ($lat1 * pi() ) / 180;
		 $lng1 = ($lng1 * pi() ) / 180;

		 $lat2 = ($lat2 * pi() ) / 180;
		 $lng2 = ($lng2 * pi() ) / 180;

		 /*
		   Using the
		   Haversine formula

		   http://en.wikipedia.org/wiki/Haversine_formula

		   calculate the distance
		 */

		 $calcLongitude = $lng2 - $lng1;
		 $calcLatitude = $lat2 - $lat1;
		 $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
		 $calculatedDistance = $earthRadius * $stepTwo;

		 return round($calculatedDistance);
	 }

	
}
